package com.similarworld.service;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.similarworld.dao.AbstractDAO;
import com.similarworld.dao.ItemDao;
import com.similarworld.model.Item;
import com.similarworld.model.ItemRate;
import com.similarworld.type.ItemStatus;

@Service
public class ItemService extends AbstractService<Item> {

	@Autowired
	ItemDao dao;
	
	@Override
	protected AbstractDAO<Item> getDAO() {
		return dao;
	}

	public List<Item> getActiveItems(int count) {
		return dao.getItems(ItemStatus.ACTIVE, count);
	}

	/**
	 * Bir item rate kaydedilirken
	 * ona ait item de bulunan rate
	 * alanida guncellenmelidir.
	 * */
	public void saveItemRate(ItemRate itemRate) {
		if(itemRate.getId() == null) {
			this.mergeAnyModel(itemRate);
			Item item = itemRate.getItem();
			Long count = null == item.getRateCount() ? 0l : item.getRateCount();
			count++;
			Integer rate = item.getRate() + itemRate.getRate();
			rate = (int) (((double)(rate)/((double)count)));
			item.setRate(rate);
			item.setRateCount(count);
			this.mergeAnyModel(item);
		} else {
			this.mergeAnyModel(itemRate);
			Item item = itemRate.getItem();
			Long count = item.getRateCount();
			Integer rate = item.getRate() + itemRate.getRate();
			rate = (int) (((double)(rate)/((double)count)));
			item.setRate(rate);
			this.mergeAnyModel(item);
		}
		
	}
	
}
